<?php 
namespace app\v2\logic;
use think\Model;
use think\Db;
use app\v2\model\Apply;
use app\admin\logic\Pay;
use app\v2\model\Pay as OPay;
use app\v2\model\Order;
use app\v2\model\Fuiou;
class Repayment extends Model
{
    //处理需要扣款的数据
    public function handleRepayment()
    {
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d',strtotime('+1 day'));
        $where['appoint_time'] = [['egt',$today],['lt',$tomorrow]];
        $where['status'] = 3;
        //获取符合条件的申请数据
        $paymentOrder = new Apply;
        $result = $paymentOrder->getDataList('order_number',$where);
        if(count($result) > 0)
        {
            foreach($result as $v){
                $this->repay($v->order_number);
            }
        }
        


    }
    /**
     * [repay 创建订单并向富友发起扣款]
     * @param  string $apply_id [description]
     * @return [type]           [description]
     */
    public function repay($apply_id = '', $phone = '')
    {
        if(!$apply_id)
        {
            $this->error = '参数错误';
            return false;
        }
        //获取金额
        $pay = new Pay;
        $re = json_decode($pay->repaymentPlan($apply_id),true);
        //获取请求的数据
        $paymentOrder = new Apply;
        $data = $paymentOrder->getDatas('a.uid,a.name,a.order_number,a.bank_card_number,a.id_card,a.phone bind_phone,a.contract_number repayment_no,b.no_agree,c.no_order',['a.order_number'=>$apply_id])->toArray();
        $data['money_order'] = $re['repaymentPlan']['amount'];
        $param['order_number'] = $apply_id;
        $param['pay_type'] = 1;
        $param['pay_money'] = $data['money_order'];
        //创建订单
        $order = new Order;
        $orderRe =  $order->createorder2($param);
        if(!$orderRe)
        {
            file_put_contents(LOGS_DIR_NAME."createOrderError.txt", '创建时间:'.date('Y-m-d H:i:s',time())." 结果:创建失败:".$order->getError().'---'.json_encode($param)."\n\n", FILE_APPEND);
            $this->error = $order->getError();
            return false;
        }
        $data['no_order'] = $orderRe['no_order'];
        $fuiou = new Fuiou;
        $res = $fuiou->repay($orderRe['no_order'], $phone);
        file_put_contents(LOGS_DIR_NAME."repayAll.txt", '时间:'.date('Y-m-d H:i:s',time())." 结果:自动还款日志:".$fuiou->getError().'---'.json_encode($param)."\n\n", FILE_APPEND);
        //处理
        if(!$res)
        {
            file_put_contents(LOGS_DIR_NAME."repayError.txt", '时间:'.date('Y-m-d H:i:s',time())." 结果:自动还款失败:".$fuiou->getError().'---'.json_encode($param)."\n\n", FILE_APPEND);
            $this->error = $fuiou->getError();
            return false;
        }    

        return '处理成功';    
    }

}

 ?>